<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>1206_getSnapshotBeforeUpdate应用场景-生命周期(新)</title>
  <style>
    .list{
      width: 200px;
      height: 150px;
      background-color: skyblue;
      overflow: auto;
    }
    .news{
      height: 30px;
    }
  </style>
</head>

<body>
  <div id="news"></div>
  <!-- react核心库 -->
  <script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
  <!-- 用于支持react操作DOM -->
  <script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
  <!-- 用于将jsx转为js -->
  <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

  <script type="text/babel">

    /**
     * 创建组件
     *  生命周期函数：生命周期钩子函数
     */
    class NewsList extends React.Component {

      state = {newsArr: []}
      

      componentDidMount() {
        setInterval(() => {
          // 获取原状态
          const {newsArr} = this.state
          const news = '新闻' + (newsArr.length + 1)
          // 更新状态
          this.setState({newsArr: [news, ...newsArr]})
        }, 1000);
      }


      getSnapshotBeforeUpdate() {
        // 获取内容高度
        return this.refs.list.scrollHeight
      }

    componentDidUpdate(prevProps, prevState, prevHeight) {
      // 滚动条持续滚动
       this.refs.list.scrollTop += this.refs.list.scrollHeight - prevHeight
    }

      /**
       * 初始化渲染，状态更新重新渲染
       */
      render() {
        return (
          <div className="list" ref='list'>
            {
              this.state.newsArr.map((n, index) => {
                return <div className="news" key={index}>{n}</div>
              })
            }
          </div>
        )
      }
    }

    // 2.渲染虚拟DOM到页面
    ReactDOM.render(<NewsList/>, document.getElementById('news'))

  </script>
</body>

</html>